<template>
	<view class="page-container">
		<!-- 自定义导航栏 -->
		<view class="nav-bar">
			<text class="nav-title">购物车</text>
			<text class="nav-action" @click="toggleEdit">{{ isEditMode ? '完成' : '编辑' }}</text>
		</view>

		<!-- 空购物车 -->
		<view class="empty-cart-wrapper" v-if="!cartItems.length">
			<image src="/static/cart/empty-cart.png" mode="aspectFit" class="empty-icon"></image>
			<text class="empty-text">购物车还是空的，快去逛逛吧～</text>
			<button class="go-shopping-btn" @click="goShopping">去逛逛</button>
		</view>

		<!-- 购物车列表 -->
		<scroll-view v-else class="cart-scroll" scroll-y>
			<view class="cart-card">
				<view class="card-header">
					<image src="/static/logo.png" class="shop-icon" />
					<text class="shop-name">狗道宠物商城</text>
				</view>
				<view class="cart-list">
					<view class="cart-item" v-for="(item, index) in cartItems" :key="item.id">
						<u-checkbox-group>
							<u-checkbox :checked="item.selected" @change="toggleSelect(item)" shape="circle"
								activeColor="#FF7043"></u-checkbox>
						</u-checkbox-group>

						<image class="product-image" :src="formatImageUrl(item.image)"
							mode="aspectFill" @click="navigateToDetail(item.productId)"></image>

						<view class="product-info">
							<text class="product-name">{{ item.name }}</text>
							<text class="product-spec">{{ item.spec || '默认规格' }}</text>

							<view class="price-quantity">
								<text class="product-price">¥{{ item.price }}</text>
								<u-number-box v-model="item.quantity" @change="updateCartItem(index)"></u-number-box>
							</view>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>

		<!-- 推荐商品 -->
		<view class="recommend-section">
			<view class="section-title">
				<text>为你推荐</text>
			</view>
			<view class="recommend-list">
				<view class="product-item" v-for="item in recommendList" :key="item.id">
					<view class="image-container">
						<image :src="item.image" mode="aspectFit" class="product-image"></image>
					</view>
					<view class="product-info-rec">
						<text class="product-name-rec">{{ item.name }}</text>
						<text class="product-price-rec">¥{{ item.price }}</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 底部结算栏 -->
		<view class="cart-footer">
			<view class="footer-left">
				<u-checkbox-group>
					<u-checkbox :checked="isAllSelected" @change="toggleSelectAll" shape="circle" activeColor="#FF7043">
						<text class="select-all-text">全选</text>
					</u-checkbox>
				</u-checkbox-group>
			</view>

			<view class="footer-right" v-if="!isEditMode">
				<view class="total-price">
					<text class="total-label">合计：</text>
					<text class="total-value">¥{{ totalPrice }}</text>
				</view>
				<button class="settle-btn" @click="goSettle()">去结算({{ selectedCount }})</button>
			</view>
			<view class="footer-right" v-else>
				<button class="delete-btn" @click="deleteSelected()">删除</button>
			</view>
		</view>

		<!-- 添加自定义TabBar组件 -->
		<custom-tab-bar></custom-tab-bar>
	</view>
</template>

<script>
import CustomTabBar from '@/components/CustomTabBar.vue'
import uCheckbox from '@/node_modules/uview-ui/components/u-checkbox/u-checkbox.vue'
import uCheckboxGroup from '@/node_modules/uview-ui/components/u-checkbox-group/u-checkbox-group.vue'
import uNumberBox from '@/node_modules/uview-ui/components/u-number-box/u-number-box.vue'
import { formatImageUrl } from '../../src/utils/imageTools.js';

export default {
	components: {
		CustomTabBar,
		uCheckbox,
		uCheckboxGroup,
		uNumberBox
	},
	data() {
		return {
			isEditMode: false,
			cartItems: [],
			recommendList: [
				{
					id: 1,
					name: '地狱厨房猫零食...',
					price: 13.8,
					image: '/static/recommend-1.jpg'
				},
				{
					id: 2,
					name: '鲜朗猫湿粮主食...',
					price: 65,
					image: '/static/recommend-2.jpg'
				},
				{
					id: 3,
					name: '那非普吡虫啉狗...',
					price: 60,
					image: '/static/recommend-3.jpg'
				},
				{
					id: 4,
					name: '多格漫犬零食...',
					price: 6.8,
					image: '/static/recommend-4.jpg'
				},
				{
					id: 5,
					name: '维可派狗零食农...',
					price: 16.8,
					image: '/static/recommend-5.jpg'
				},
				{
					id: 6,
					name: '伊纳宝烤鸡小胸...',
					price: 7.8,
					image: '/static/recommend-6.jpg'
				}
			],
			tabList: [
				{ name: 'shop', text: '商城', icon: '/static/tabbar/商城.png', url: '/pages/shop/index' },
				{ name: 'category', text: '分类', icon: '/static/tabbar/分类.png', url: '/pages/category/index' },
				{ name: 'selection', text: '狗道甄选', icon: '/static/tabbar/狗道甄选.png', url: '/pages/selection/index' },
				{ name: 'cart', text: '购物车', icon: '/static/tabbar/购物车.png', url: '/pages/cart/index' },
				{ name: 'my', text: '我的', icon: '/static/tabbar/我的.png', url: '/pages/my/index' }
			]
		}
	},
	computed: {
		isAllSelected() {
			return this.cartItems.length > 0 && this.cartItems.every(item => item.selected);
		},
		selectedCount() {
			return this.cartItems.filter(item => item.selected).length;
		},
		totalPrice() {
			return this.cartItems
				.filter(item => item.selected)
				.reduce((total, item) => total + item.price * item.quantity, 0)
				.toFixed(2);
		}
	},
	onShow() {
		// 每次显示页面时重新加载购物车数据
		this.loadCartItems();
	},
	methods: {
		formatImageUrl,
		loadCartItems() {
			this.$api.cartApi.getList()
				.then(res => {
					console.log('购物车数据:', res)
					if (res && res.code === 200 && res.data) {
						// 将 'selected' 字段转换为布尔值以匹配组件期望
						this.cartItems = res.data.map(item => ({
							...item,
							selected: !!item.selected
						}));
					}
				})
				.catch(err => {
					console.error('获取购物车数据失败:', err)
					uni.showToast({
						title: '获取购物车数据失败',
						icon: 'none'
					})
				})
		},
		goShopping() {
			uni.switchTab({ url: '/pages/shop/index' });
		},
		switchTab(url) {
			uni.switchTab({ url });
		},
		toggleEdit() {
			this.isEditMode = !this.isEditMode;
		},
		toggleSelect(item) {
			item.selected = !item.selected;
			this.$api.cartApi.update({
				id: item.id,
				selected: item.selected ? 1 : 0
			}).catch(err => {
				console.error('更新选中状态失败:', err);
				// 如果更新失败，将状态恢复
				item.selected = !item.selected;
				uni.showToast({
					title: '状态更新失败',
					icon: 'none'
				});
			});
		},
		toggleSelectAll() {
			const newStatus = !this.isAllSelected;
			this.cartItems.forEach(item => {
				item.selected = newStatus;
			});
		},
		increase(idx) {
			this.cartItems[idx].quantity++;
		},
		decrease(idx) {
			if (this.cartItems[idx].quantity > 1) {
				this.cartItems[idx].quantity--;
			}
		},
		updateCartItem(index) {
			const item = this.cartItems[index];
			this.$api.cartApi.update({
				id: item.id,
				quantity: item.quantity
			})
				.then(res => {
					console.log('更新购物车成功:', res)
				})
				.catch(err => {
					console.error('更新购物车失败:', err)
					uni.showToast({
						title: '更新购物车失败',
						icon: 'none'
					})
				})
		},
		deleteSelected() {
			const selectedIds = this.cartItems
				.filter(item => item.selected)
				.map(item => item.id);

			if (selectedIds.length === 0) {
				uni.showToast({
					title: '请选择要删除的商品',
					icon: 'none'
				});
				return;
			}

			uni.showModal({
				title: '提示',
				content: '确定要删除选中的商品吗？',
				success: res => {
					if (res.confirm) {
						this.$api.cartApi.deleteItems({
							ids: selectedIds
						})
							.then(res => {
								console.log('删除购物车商品成功:', res)
								// 更新本地购物车数据
								this.cartItems = this.cartItems.filter(item => !item.selected);
								if (this.cartItems.length === 0) {
									this.isEditMode = false;
								}

								uni.showToast({
									title: '删除成功',
									icon: 'success'
								})
							})
							.catch(err => {
								console.error('删除购物车商品失败:', err)
								uni.showToast({
									title: '删除失败',
									icon: 'none'
								})
							})
					}
				}
			})
		},
		deleteOne(idx) {
			this.cartItems.splice(idx, 1);
			if (this.cartItems.length === 0) {
				this.isEditMode = false;
			}

			// 将选中的商品ID传递给订单确认页面
			const selectedItems = this.cartItems.filter(item => item.selected);
			uni.setStorageSync('confirmOrderItems', selectedItems);

			uni.navigateTo({
				url: '/pages/order/confirm'
			});
		},
		goSettle() {
			// 检查是否有选中的商品
			const selectedItems = this.cartItems.filter(item => item.selected);
			if (selectedItems.length === 0) {
				uni.showToast({
					title: '请选择要结算的商品',
					icon: 'none'
				});
				return;
			}

			// 将选中的商品信息存储到本地，传递给订单确认页面
			uni.setStorageSync('orderItems', selectedItems);

			// 跳转到订单确认页面
			uni.navigateTo({
				url: '/pages/order/confirm'
			});
		},
		addToCart(item) {
			uni.showToast({ title: '已添加', icon: 'success' });
			// 实际应将商品加入购物车
		}
	}
}
</script>

<style lang="scss">
.page-container {
	background-color: $page-bg-color;
	min-height: 100vh;
	padding-bottom: 120rpx; // 为底部操作栏留出空间
}

// 自定义导航栏
.nav-bar {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 90rpx 30rpx 20rpx; // 适配状态栏高度
	background-color: #fff;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.02);
	position: sticky;
	top: 0;
	z-index: 99;

	.nav-title {
		font-size: 36rpx;
		font-weight: bold;
		color: $text-primary-color;
	}

	.nav-action {
		font-size: 28rpx;
		color: #333;
	}
}

// 空购物车
.empty-cart-wrapper {
	display: flex;
	flex-direction: column;
	text-align: center;
	padding-top: 200rpx;

	.empty-icon {
		width: 280rpx;
		height: 280rpx;
	}

	.empty-text {
		display: block;
		margin: 30rpx 0;
		color: $text-secondary-color;
	}

	.go-shopping-btn {
		display: inline-flex;
		width: auto;
		padding: 0 60rpx;
		height: 76rpx;
		line-height: 76rpx;
		background: $theme-color;
		color: #fff;
		border-radius: 38rpx;
		font-size: 28rpx;
	}
}


// 购物车列表
.cart-scroll {
	height: calc(100vh - 230rpx); // 减去导航栏和底部操作栏高度
}

.cart-card {
	background-color: $card-bg-color;
	border-radius: 20rpx;
	margin: 20rpx 30rpx;
	padding: 20rpx;
	box-shadow: $shadow;

	.card-header {
		display: flex;
		align-items: center;
		padding-bottom: 20rpx;
		border-bottom: 1rpx solid #F0EAE6;

		.shop-icon {
			width: 40rpx;
			height: 40rpx;
			margin-right: 15rpx;
		}

		.shop-name {
			font-size: 28rpx;
			color: $text-primary-color;
		}
	}
}

.cart-item {
	display: flex;
	padding: 20rpx 0;
	align-items: center;

	.product-image {
		width: 160rpx;
		height: 160rpx;
		border-radius: 12rpx;
		background-color: #f8f8f8;
		margin: 0 20rpx;
	}

	.product-info {
		flex: 1;
		display: flex;
		flex-direction: column;
		height: 180rpx;
		justify-content: space-between;

		.product-name {
			font-size: 27rpx;
			color: $text-primary-color;
			line-height: 1.4;
			
			/* 以下是新增的样式，用于处理长文本 */
			overflow: hidden;
			text-overflow: ellipsis;
			display: -webkit-box;
			-webkit-line-clamp: 2; /* 限制在两行 */
			-webkit-box-orient: vertical;
			white-space: normal; /* 允许换行 */
		}

		.product-spec {
			font-size: 24rpx;
			color: $text-secondary-color;
			background-color: $page-bg-color;
			padding: 4rpx 10rpx;
			border-radius: 6rpx;
			align-self: flex-start;
			margin-top: 8rpx;
		}

		.price-quantity {
			margin-top: auto;
			display: flex;
			justify-content: space-between;
			align-items: center;

			.product-price {
				font-size: 32rpx;
				font-weight: bold;
				color: $theme-color;
			}
		}
	}
}


// 推荐商品
.recommend-section {
	padding: 0 30rpx;
	margin-top: 40rpx;

	.section-title {
		text-align: center;
		margin-bottom: 30rpx;
		font-size: 32rpx;
		font-weight: bold;
		color: $text-primary-color;
	}

	.recommend-list {
		display: flex;
		flex-wrap: wrap;
		justify-content: space-between;

		.product-item {
			width: 48.5%;
			background-color: $card-bg-color;
			border-radius: 16rpx;
			overflow: hidden;
			margin-bottom: 25rpx;
			box-shadow: $shadow;

			.image-container {
				width: 100%;
				height: 320rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				background-color: #f8f8f8;
			}

			.product-image {
				width: 100%;
				height: 100%;
				object-fit: contain;
			}

			.product-info-rec {
				padding: 20rpx;

				.product-name-rec {
					font-size: 28rpx;
					color: $text-primary-color;
					line-height: 1.4;
					white-space: nowrap;
					overflow: hidden;
					text-overflow: ellipsis;
				}

				.product-price-rec {
					font-size: 34rpx;
					color: $theme-color;
					font-weight: bold;
					margin-top: 15rpx;
					display: block;
				}
			}
		}
	}
}

// 底部结算栏
.cart-footer {
	position: fixed;
	bottom: 100rpx; // 适配TabBar高度
	left: 0;
	right: 0;
	height: 120rpx;
	background-color: #fff;
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 0 30rpx;
	box-shadow: 0 -2rpx 12rpx rgba(0, 0, 0, 0.05);
	z-index: 99;

	.footer-left {
		.select-all-text {
			margin-left: 10rpx;
			color: $text-primary-color;
		}
	}

	.footer-right {
		display: flex;
		align-items: center;

		.total-price {
			margin-right: 20rpx;

			.total-label {
				font-size: 28rpx;
				color: $text-primary-color;
			}

			.total-value {
				font-size: 36rpx;
				font-weight: bold;
				color: $theme-color;
			}
		}

		.settle-btn,
		.delete-btn {
			padding: 0 40rpx;
			height: 80rpx;
			line-height: 80rpx;
			border-radius: 40rpx;
			font-size: 28rpx;
			color: #fff;
		}

		.settle-btn {
			background: $theme-color;
		}

		.delete-btn {
			background: #e53935; // 删除用红色
		}
	}
}
</style>